using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using FinanceStats.Business;
using FinanceStats.Common;
using Informatika.Common;
using System.IO;
using FinanceStats.ReportingService;
using System.Threading;


namespace FinanceStats
{
    public partial class TotalReportForm : Form
    {
        private long userID;

        private string startDate;
        private Guid? reportID;

        // reporting services instances
        ReportingService.ReportingService2005 rs;
        ExecutionService.ReportExecutionService rsExec;

        public string StartDate
        {
            get { return startDate; }
            set { startDate = value; }
        }
        private string endDate;

        public string EndDate
        {
            get { return endDate; }
            set { endDate = value; }
        }
        private string fileName;

        public string FileName
        {
            get { return fileName; }
            set { fileName = value; }
        }


        private string _reportName;

        public TotalReportForm(long userID)
        {
            this.userID = userID;
            InitializeComponent();
            InitializeServices();
        }

        private void InitializeServices()
        {
            // initializing reporting services
            this.rs = new ReportingService.ReportingService2005();
            this.rsExec = new FinanceStats.ExecutionService.ReportExecutionService();
            rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
            rsExec.Credentials = System.Net.CredentialCache.DefaultCredentials;

            rs.Url = AppSettingsHelper.GetWebConfigValue(Constants.ReportingServiceURL);
            rsExec.Url = AppSettingsHelper.GetWebConfigValue(Constants.ReportExecutionServiceURL);
        }


        private void button1_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(this.textBox1.Text))
            {
                this.statusStrip1.Visible = true;
                ThreadPool.QueueUserWorkItem(new WaitCallback(this.GenerateReport));
             }
        }

        private void ToggleGUI(bool value)
        {
            this.button1.Enabled = value;
            this.button2.Enabled = value;
            this.statusStrip1.Visible = !value;
        }

        private void GenerateReport(object args)
        {
            ToggleGUI(false);
            this.startDate = dateTimePicker1.Value.ToString("yyyy-MM-dd");
            this.endDate = dateTimePicker2.Value.ToString("yyyy-MM-dd");
            this._reportName = AppSettingsHelper.GetWebConfigValue(Constants.TotalReportPath);
            bool _forRendering = false;

            this.fileName = textBox1.Text;
            string _historyID = null;
            string historyID = null;
            ParameterValue[] _values = null;
            DataSourceCredentials[] _credentials = null;
            ReportParameter[] _parameters = null;

            try
            {
                _parameters = rs.GetReportParameters(_reportName, _historyID,
                                  _forRendering, _values, _credentials);
                // Load the selected report.
                ExecutionService.ExecutionInfo ei =
                      rsExec.LoadReport(_reportName, historyID);

                // Set the parameters for the report needed.
                ExecutionService.ParameterValue[] parameters =
                       new ExecutionService.ParameterValue[2];

                // Place to include the parameter.
                if (_parameters.Length > 0)
                {
                    parameters[0] = new ExecutionService.ParameterValue();
                    parameters[0].Label = "StartDate";
                    parameters[0].Name = "StartDate";
                    parameters[0].Value = this.StartDate;
                    parameters[1] = new ExecutionService.ParameterValue();
                    parameters[1].Label = "EndDate";
                    parameters[1].Name = "EndDate";
                    parameters[1].Value = this.EndDate;
                }

                rsExec.SetExecutionParameters(parameters, "en-us");
                string format = "PDF";
                string deviceInfo = null;
                string exstension = null;
                string mimeType = null;
                string encoding = null;
                ExecutionService.Warning [] warnings = null;
                string [] streamIds = null;
                byte[] res = rsExec.Render(format, deviceInfo, out exstension, out mimeType, out encoding, out warnings, out streamIds);
                string fileName = this.FileName;
                using (FileStream stream = File.OpenWrite(fileName))
                {
                    stream.Write(res, 0, res.Length);
                }
                ToggleGUI(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (this.saveFileDialog1.ShowDialog(this) == DialogResult.OK && this.saveFileDialog1.FileName != "")
            {
                this.textBox1.Text = saveFileDialog1.FileName;
            }
        }

        private void CheckedChanged(object sender, EventArgs e)
        {
            RadioButton rb = sender as RadioButton;
            if (rb == radioButton1)
            {
                SetWeekly();
            }
            else if (rb == radioButton2)
            {
                SetMonthly();
            }
            else if (rb == radioButton3)
            {
                SetYearly();
            }
            else if (rb == radioButton4)
            {
                SetEver();
            }
            else
            {
                TogglePickers(true);
            }
        }

        private void SetWeekly()
        {
            TogglePickers(false);
            DateTime today = DateTime.Today;
            while (today.DayOfWeek != DayOfWeek.Monday)
            {
                today = today.AddDays(-1);
            }
            dateTimePicker1.Value = today;
            dateTimePicker2.Value = today.AddDays(6);
        }

        private void SetMonthly()
        {
            TogglePickers(false);
            DateTime today = DateTime.Today;
            while (today.Day != 1)
            {
                today = today.AddDays(-1);
            }
            dateTimePicker1.Value = today;
            dateTimePicker2.Value = today.AddMonths(1).AddDays(-1);
        }

        private void SetYearly()
        {
            TogglePickers(false);
            DateTime today = DateTime.Today;
            while (today.DayOfYear != 1)
            {
                today = today.AddDays(-1);
            }
            dateTimePicker1.Value = today;
            dateTimePicker2.Value = today.AddYears(1).AddDays(-1);
        }

        private void SetEver()
        {
            TogglePickers(false);
            dateTimePicker1.Value = DataManager.Instance.GetFirstDate(userID);
            dateTimePicker2.Value = DataManager.Instance.GetLastDate(userID);
        }

        private void TogglePickers(bool value)
        {
            dateTimePicker1.Enabled = value;
            dateTimePicker2.Enabled = value;
        }

        private void TotalReportForm_Load(object sender, EventArgs e)
        {
            this.radioButton1.Checked = true;
        }
    }
}